<script>
	// require("sdk/libs/strophe");
	let WebIM = require("@/utils/WebIM")["default"];
	let msgStorage = require("@/components/chat/msgstorage");
	let msgType = require("@/components/chat/msgtype");
	let disp = require("@/utils/broadcast");
	import {
		mapGetters
	} from 'vuex'
	import {
		getCurrentRoute
	} from '@/utils/index.js'
	export default {
		globalData: {
			unReadMessageNum: 0,
			userInfo: null,
			saveGroupInvitedList: [],
			isIPX: false, //是否为iphone X,
			hxForm: {},
			login({
				hxPassword,
				hxUsername
			}) {
				// uni.showLoading({
				// 	mask:true,
				// 	title:'正在登录中...'
				// })
				this.hxForm = {
					hxPassword,
					hxUsername
				}
				return new Promise((resolve, reject) => {
					WebIM.conn.open({
						apiUrl: WebIM.config.apiURL,
						user: hxUsername,
						pwd: hxPassword,
						grant_type: 'password',
						appKey: WebIM.config.appkey,
						success: res => {
							uni.setStorage({
								key: "myUsername",
								data: hxUsername.toLocaleLowerCase()
							});
							if (this.unReadMessageNum > 0) {
								uni.setTabBarBadge({
									index: 3, //tab下标
									text: this.unReadMessageNum + '' //要设置的内容
								})
							}
							console.log('环信登录成功')
							resolve()
							//uni.hideLoading()
						},
						error: e => {
							reject()
						}
					})
				})
			},
			//退出登录
			close(){
				if(!WebIM.conn){
					return Promise.resolve(true)
				}
				WebIM.conn&&WebIM.conn.close&&WebIM.conn.close()
			},
			checkIsIPhoneX() {
				uni.getSystemInfo({
					success: res => this.isIPX = res.model.indexOf("iPhone X") != -1
				});
			}
		},
		data() {
			return {
				innerAudioContext: null,
				music: null
			}
		},
		onLaunch(options) {
			var me = this;
			var logs = uni.getStorageSync("logs") || [];
			logs.unshift(Date.now());
			uni.setStorageSync("logs", logs); //
			disp.on("em.main.ready", me.calcUnReadSpot);
			disp.on("em.chat.session.remove", me.calcUnReadSpot);
			disp.on("em.chat.audio.fileLoaded", me.calcUnReadSpot);
			disp.on("em.main.deleteFriend", me.calcUnReadSpot);
			disp.on("em.chat.audio.fileLoaded", me.calcUnReadSpot);
			disp.on("em.chatroom.leave", me.calcUnReadSpot);
			disp.on("em.chat.readyNum", () => {
				me.calcUnReadSpot();
			});
			this.initListen()
			this.getAllunReadMsg() //获取未读消息总计条数
			//this.initSocket('/ws/webSocket/driveCar') //初始化通知socket

			this.$store.dispatch('getAppParam')
			if (uni.canIUse('getUpdateManager')) {
				const updateManager = uni.getUpdateManager()
				console.log(updateManager)
				if(!updateManager) return false;
				updateManager.onCheckForUpdate(function(res) {
					if (res.hasUpdate) {
						updateManager.onUpdateReady(function() {
							uni.showModal({
								title: '更新提示',
								content: '新版本已经准备好，是否重启应用？',
								success: function(res) {
									res.confirm&&updateManager.applyUpdate()
								}
							})
						})
						updateManager.onUpdateFailed(function() {
							uni.showModal({
								title: '已经有新版本了哟~',
								content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
							})
						})
					}
				})
			} else {
				uni.showModal({
					title: '提示',
					content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
				})
			}
		},
		onShow({
			scene
		}) {
			this.$store.dispatch('scene', scene)
			this.innerAudioContext = uni.createInnerAudioContext();
			//设置tabbar的颜色样式
			//根据当前时间设置显示 
			// const isDark = this.currentTheme==='dark'
			// uni.setTabBarStyle({
			// 	color: '#999999',
			// 	backgroundColor: isDark  ? "#1B1926" : "#fcfcfc"
			// });
		},
		onHide() {
			console.log('App Hide')
		},
		computed: {
			...mapGetters(['loginForm'])
		},
		methods: {
			// 处理未读消息回执
			ack(receiveMsg) {
				// 处理未读消息回执
				var bodyId = receiveMsg.id; // 需要发送已读回执的消息id

				var ackMsg = new WebIM.message("read", WebIM.conn.getUniqueId());
				ackMsg.set({
					id: bodyId,
					to: receiveMsg.from
				});
				WebIM.conn.send(ackMsg.body);
			},
			onMessageError(err) {
				if (err.type === "error") {
					uni.showToast({
						title: err.errorText
					});
					return false;
				}
				return true;
			},
			setMessage(message, type) {
				message && msgStorage.saveReceiveMsg(message, type);
				this.calcUnReadSpot(message);
				this.ack(message);
			},
			saveGroups() {
				var me = this;
				return WebIM.conn.getGroup({
					limit: 50,
					success: function(res) {
						uni.setStorage({
							key: "listGroup",
							data: res.data
						});
					},
					error: function(err) {
						console.log(err);
					}
				});
			},
			audio(e) {
				let _this = this;
				const innerAudioContext = this.innerAudioContext;
				if (_this.music == e) {
					if (innerAudioContext.paused) {
						innerAudioContext.play()
					} else {
						innerAudioContext.pause()
						innerAudioContext.onPause(() => {
							innerAudioContext.startTime = innerAudioContext.currentTime
						})
					}

				} else {
					innerAudioContext.src = e
					if (innerAudioContext.paused) {
						innerAudioContext.play()
					} else {
						innerAudioContext.pause()
						innerAudioContext.onPause(() => {
							innerAudioContext.startTime = innerAudioContext.currentTime
						})
					}
				}
				_this.music = e
			},
			//初始化im
			initListen() {
				// const myname = uni.getStorageSync("myUsername");
				// !this.$store.getters.token ? uni.navigateTo({url: "/pagesA/register/register"}) : this.globalData.login(this.$store.getters.loginForm)
				const me = this;
				WebIM.conn.listen({
					onOpened(message) {},

					onReconnect() {
						console.log("重连中...")
						uni.showToast({
							title: "重连中...",
							duration: 2000
						});
					},

					onSocketConnected() {
						uni.showToast({
							title: "socket连接成功",
							duration: 2000
						});
					},

					onClosed() {
						// uni.showToast({
						// 	title: "网络已断开",
						// 	icon: "none",
						// 	duration: 2000
						// });
						console.info('关闭了！！！！！！！！！！！！！！')
						// uni.redirectTo({
						// 	url: "/pagesA/login/login?type=login",
						// });
						WebIM.conn.close();
						me.globalData.login(me.globalData.hxForm)
					},
					onInviteMessage(message) {
						me.globalData.saveGroupInvitedList.push(message);
						disp.fire("em.invite.joingroup", message); // uni.showModal({
						// 	title: message.from + " 已邀你入群 " + message.roomid,
						// 	success(){
						// 		disp.fire("em.invite.joingroup", message);
						// 	},
						// 	error(){
						// 		disp.fire("em.invite.joingroup", message);
						// 	}
						// });
					},

					onReadMessage(message) {
						//console.log('已读', message)
					},

					onPresence(message) {
						//console.log("onPresence", message);
						switch (message.type) {
							case "unsubscribe":
								break;
								// 好友邀请列表
							case "subscribe":
								if (message.status === "[resp:true]") {} else {
									// pages[0].handleFriendMsg(message);
									for (let i = 0; i < me.globalData.saveFriendList.length; i++) {
										if (me.globalData.saveFriendList[i].from === message.from) {
											me.globalData.saveFriendList[i] = message;
											disp.fire("em.subscribe");
											return;
										}
									}

									me.globalData.saveFriendList.push(message);
									disp.fire("em.subscribe");
								}

								break;

							case "subscribed":
								uni.showToast({
									title: "添加成功",
									duration: 1000
								});
								disp.fire("em.subscribed");
								break;

							case "unsubscribed":
								// uni.showToast({
								// 	title: "已拒绝",
								// 	duration: 1000
								// });
								disp.fire("em.unsubscribed");
								break;
								//直接进群
							case "direct_joined":
								me.saveGroups();
								// uni.showToast({
								// 	title: "已进群",
								// 	duration: 1000
								// });
								break;
								//同意加入
							case "memberJoinPublicGroupSuccess":
								me.saveGroups();
								// uni.showToast({
								// 	title: "已进群",
								// 	duration: 1000
								// });
								break;
							case "invite":
								let info = message.from + "邀请你加入群组";
								uni.showModal({
									title: "提示",
									content: info,
									success(res) {
										if (res.confirm) {
											console.log("用户点击确定");
											WebIM.conn.agreeInviteIntoGroup({
												invitee: WebIM.conn.context.userId,
												groupId: message.gid,
												success: () => {
													me.saveGroups()
													console.log("加入成功");
												}
											});
										} else if (res.cancel) {
											console.log("用户点击取消");
											WebIM.conn.rejectInviteIntoGroup({
												invitee: WebIM.conn.context.userId,
												groupId: message.gid
											});
										}
									}
								});
								break;
							case "unavailable":
								disp.fire("em.contacts.remove");
								disp.fire("em.group.leaveGroup", message);
								break;

							case "deleteGroupChat":
								disp.fire("em.invite.deleteGroup", message);
								break;
								//退群监听（只有群主账号才会触发）
							case "leaveGroup":
								disp.fire("em.group.leaveGroup", message);
								break;
							case "removedFromGroup":
								disp.fire("em.group.leaveGroup", message);
								break;

							default:
								break;
						}
					},

					onRoster(message) {
						// let pages = getCurrentPages();
						// if(pages[0]){
						// 	pages[0].onShow();
						// }
					},

					onVideoMessage(message) {
						me.setMessage(message, msgType.VIDEO)
					},

					onAudioMessage(message) {
						me.setMessage(message, msgType.AUDIO)
					},
					onCustomMessage(message) {
						console.log(message, '收到消息')
						if(message.customEvent === 'red_notif'){ //仅红点提示
							if (message.customExts) {
								const redNotif = me.$store.getters.redNotif;
								const data = message.customExts;
								const {type} = data;
								if(type) redNotif[type] = true;
								me.$store.dispatch('setRedNotif',redNotif)
								// 每次推消息要保存一份数据到本地 避免用户未点击并退出后红点消失
								uni.setStorageSync(`${me.loginForm.hxUsername}notif`,redNotif)
								console.log(redNotif)
								//uni.$emit('payMoney',data)
							}
							return false;
						}
						//me.audio('https://freetyst.nf.migu.cn/public/product5th/product35/2019/09/2220/2015%E5%B9%B44%E6%9C%8824%E6%97%A5%E7%B4%A7%E6%80%A5%E5%87%86%E5%85%A5%E5%8D%83%E6%98%93%E7%9B%9F2%E9%A6%96/%E6%AD%8C%E6%9B%B2%E4%B8%8B%E8%BD%BD/MP3_40_16_Stero/6368269Z005.mp3?key=fa509183242efda6&Tim=1610361753570&channelid=00&msisdn=54bbef9b3d40472891d8d9d52504ef8c&CI=6368269Z0052600907000000563361&F=000009')
						if(message.customEvent === 'pay_money_tips'){ //付款
							// if (message.customExts) {
							// 	const data = message.customExts;
							// 	const {type} = data;
							// 	if (['payMoney'].includes(type)) { //付款通知
									
							// 	}
							// }
							if (message.customExts) {
								const data = message.customExts;
								uni.$emit('payMoney',data)
							}
							return false;
						}
						if (['drive_car_tips','gather_game_tips'].includes(message.customEvent)) {
							//上下车操作提示
							if (message.customExts) {
								const data = message.customExts;
								const {
									type
								} = data; //intoCar   outOffCar   completeCar  cancelCar  startCar readGame unReadGame
								data.customEvent = message.customEvent; //给data设置类型区分组局和展会发车
								console.log(data)
								//上车 下车 锁定车位 解锁车位 踢人 准备 取消准备
								if (['intoCar', 'outOffCar', 'lockCarPeople', 'unLockCarPeople',
										'kickOutCarPeople','intoGame', 'outOffGame', 'lockGamePeople', 'unLockGamePeople',
										'kickOutGamePeople','readGame','unReadGame'].includes(type)) {
									uni.$emit('busNotice', data)
								}
								if (['completeCar','completeGame'].includes(type)) { //测本结束
									uni.$emit('completeCar', data)
								}
								if (['cancelCar','cancelGame'].includes(type)) { //取消发车
									uni.$emit('cancelCar', data)
								}
								if (['startCar','startGame'].includes(type)) { //开始发车
									uni.$emit('startCar', data)
								}
								if (['lockCar','lockGame'].includes(type)) { //锁车
									uni.$emit('lockCar', data)
								}
								if (['unLockCar','unLockGame'].includes(type)) { //解锁车
									uni.$emit('unLockCar', data)
								}
								if (['kickOutCarPeople','kickOutGamePeople'].includes(type) && me.$store.getters.loginForm.uid == data
									.kickOutUid) { //踢人
									me.$u.toast('您被发行踢了')
									//uni.$emit('kickOutCarPeople',data)
								}
								if (['outOffExhibit', 'intoExhibit','user_authenticate'].includes(type) && me.$store.getters.token) me
									.$store.dispatch("getInfo"); //更新用户信息
							}
							return false;
						}
						me.setMessage(message, msgType[message.customEvent])
					}, //收到自定义消息
					onCmdMessage(message) {
						console.log(message, 555555)
						me.setMessage(message, msgType.CMD)
					},

					onLocationMessage(message) {
						me.setMessage(message, msgType.LOCATION)
					},
					onTextMessage(message) {
						me.setMessage(message, msgType.TEXT)
					},

					onEmojiMessage(message) {
						me.setMessage(message, msgType.EMOJI)
					},

					onPictureMessage(message) {
						me.setMessage(message, msgType.IMAGE)
					},

					onFileMessage(message) {
						me.setMessage(message, msgType.FILE)
					},

					// 各种异常
					onError(error) {
						console.log(error); // 16: server-side close the websocket connection

						if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
							// if(error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED && !logout){
							// if(WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax){
							// 	return;
							// }
							// me.$u.toast('websocket 断开，请重新登录')
							// me.$u.route({
							// 	url: "/pagesA/login/login",
							// 	params:{
							// 		type:'login'
							// 	}
							// })
							//logout = true;
							// WebIM.conn.close();
							// me.globalData.login(me.globalData.hxForm)
							console.log('重连成功', WebIM.conn)
							return;
						} // 8: offline by multi login

						if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
							// WebIM.conn.close()
							// me.globalData.login(me.globalData.hxForm)
							console.log('重连成功55')
						}

						if (error.type == WebIM.statusCode.WEBIM_CONNCTION_OPEN_ERROR) {
							uni.hideLoading();
							disp.fire("em.error.passwordErr"); // uni.showModal({
							// 	title: "用户名或密码错误",
							// 	confirmText: "OK",
							// 	showCancel: false
							// });
						}

						if (error.type == WebIM.statusCode.WEBIM_CONNCTION_AUTH_ERROR) {
							uni.hideLoading();
							disp.fire("em.error.tokenErr");
						}

						if (error.type == "socket_error") {
							///sendMsgError
							me.$u.toast('网络已断开')
							disp.fire("em.error.sendMsgErr", error);
						}
					}
				})
				me.globalData.checkIsIPhoneX();
			},
			getAllunReadMsg(cb) {
				let myName = uni.getStorageSync("myUsername");
				if (myName) {
					uni.getStorageInfo({
						success: res => {
							if (!Array.isArray(res.keys)) return false;
							const newChatMsgKeys = res.keys.filter(item => item.indexOf(myName) > -1 && item
								.indexOf('rendered_') == -1);
							let count = newChatMsgKeys.reduce(function(result, curMember, idx) {
								let chatMsgs = uni.getStorageSync(curMember) || [];
								console.log("chatMsgs: " + JSON.stringify(chatMsgs));
								if(Array.isArray(chatMsgs)){
									return result + chatMsgs.filter(val => val.style != 'self').length;
								}
								
							}, 0)
							this.globalData.unReadMessageNum = count;
							setTimeout(() => {
								cb && cb(count)
							}, 100)
						}
					})
				}
			},
			//设置消息
			calcUnReadSpot(message) {
				this.getAllunReadMsg(count => {
					if (count) {
						uni.setTabBarBadge({
							index: 3,
							text: count + ''
						})
					} else {
						uni.removeTabBarBadge({
							index: 3,
							success: () => {
								console.log('成功了')
							},
							fail: (e) => {
								console.log(e, '失败了')
							}
						})
					}
				})
			}
		},
	}
</script>

<style lang="scss">
	@import "./static/iconfont.css";
	@import "./static/index-iconfont.css";
	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import "uview-ui/index.scss";
</style>
